package hwThree4;

import edu.princeton.cs.algs4.SequentialSearchST;

import java.util.LinkedList;
import java.util.Queue;


public class SeparateChainingHastSt<Key, Value> {
    private int N;
    private int M;
    private SequentialSearchST<Key, Value>[] st;

    public SeparateChainingHastSt() {
        this(997);
    }
    public SeparateChainingHastSt(int M) {
        this.M = M;
        st = (SequentialSearchST<Key, Value>[]) new SequentialSearchST[M];
        for (int i = 0; i < M; i++) {
            st[i] = new SequentialSearchST<>();
        }
    }

    public int hash(Key key) {
        return (key.hashCode() & 0X7fffffff) & M;
    }
    public Value get(Key key) {
        return (Value) st[hash(key)].get(key);
    }
    public void put(Key key, Value val) {
        st[hash(key)].put(key,val);
    }
    public Iterable<Key> keys() {
        Queue<Key> queue = new LinkedList<>();
        for (int i = 0; i < M; i++) {
            for (Key key : st[i].keys()) {
                queue.add(key);
            }
        }
        return queue;
    }


    public static void main(String[] args) {
        SeparateChainingHastSt<Object, Object> st = new SeparateChainingHastSt<>();

        st.put("A", 1);
        st.put("B", 2);
        st.put("C", 3);
        st.put("D", 4);

        System.out.println(st.get("A")); // 输出 1
        System.out.println(st.get("B")); // 输出 2

        System.out.println(st.get("A")); // 输出 null

        for (Object key : st.keys()) {
            System.out.println(key + " => " + st.get(key));
        }
    }
}
